package cn.tinlan.shopcoin.app.discover.classify;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallClazzProxy;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;
import com.zhouyou.http.subsciber.BaseSubscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;

import butterknife.BindView;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.app.discover.classify.model.GoodsCategoryDetailModel;
import cn.tinlan.shopcoin.app.gooddetail.GoodDetailActivity;
import cn.tinlan.shopcoin.app.home.Model.ShopModel;
import cn.tinlan.shopcoin.app.home.adapter.ShopListAdapter;
import cn.tinlan.shopcoin.base.BaseActivity;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;
import io.reactivex.Observable;

/**
 * Created by Mortimer on 2018/11/28. 10:27
 * 佛祖🙏，永无bug。
 */
public class ClassifyActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.classify_titlebar)
    TitleBar classifyTitleBar;
    @BindView(R.id.classify_all)
    TextView classifyAllTV;
    @BindView(R.id.classify_num)
    TextView classifyNumTV;
    @BindView(R.id.classify_brand)
    TextView classifyBrandTV;
    @BindView(R.id.classify_price)
    TextView classifyPriceTV;

    @BindView(R.id.classify_refresh)
    SmartRefreshLayout classifyRefresh;
    @BindView(R.id.classify_rv)
    RecyclerView classifyRView;


    private ShopListAdapter mShopListAdapter;
    private List<GoodsCategoryDetailModel> mShopModels;
    private String goodCategoryId;

    private int sort_price; //(1小到大，2大到小)
    private int sort_sale; //(1小到大，2大到小)
    public  int page = 1;
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_classify;
    }

    @Override
    public void initView() {
        super.initView();

        drawableDefaultBar();
        initTitleBar();
        //中间的按钮选项
        initClassifyOptions();
        initRView();
        initClassifyRefresh();
    }




    private void initTitleBar() {
        classifyTitleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
    }

    private void initClassifyOptions() {
        classifyAllTV.setOnClickListener(this);
        classifyNumTV.setOnClickListener(this);
        classifyBrandTV.setOnClickListener(this);
        classifyPriceTV.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.classify_all:
                reloadClassifyPriceTV();
                sort_sale  = 0;
                page = 1;
                getClassifyData(page,sort_price,sort_sale);
                break;
            case R.id.classify_num:
                reloadClassifyPriceTV();
                if (sort_sale == 0 || sort_sale == 1) {
                    sort_sale = 2;
                }else {
                    sort_sale = 1;
                }
                page = 1;
                getClassifyData(page,sort_price,sort_sale);
                break;
            case R.id.classify_brand:

                break;
            case R.id.classify_price:
                sort_sale = 0;
                if (sort_price == 0 || sort_price == 1) {
                    sort_price = 2;
                    Drawable drawable = getResources().getDrawable(R.drawable.price_up);
                    drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
                    classifyPriceTV.setCompoundDrawables(null,null,drawable,null);
                }else {
                    reloadClassifyPriceTV();
                    sort_price = 1;
                }
                page = 1;
                getClassifyData(page,sort_price,sort_sale);
                break;
        }
    }

    //重置价格右侧的尖头
    private void reloadClassifyPriceTV() {
        if (sort_price == 2) {
            sort_price = 0;
            Drawable drawable = getResources().getDrawable(R.drawable.price_down);
            drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
            classifyPriceTV.setCompoundDrawables(null,null,drawable,null);
        }
    }


    private void initRView() {
        GridLayoutManager gm = new GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false);
//        {
//
//            @Override
//            public boolean canScrollVertically() {
//            return false;
//        }
//        }
//        List<ShopModel> datas =
//        for (int i = 0 ; i< 2; i++){
//            datas.add(new ShopModel(R.drawable.ads_1,""));
//        }
        mShopModels = new ArrayList<>();
        classifyRView.setLayoutManager(gm);
//        rvShopList.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        classifyRView.setItemAnimator(new DefaultItemAnimator());
        mShopListAdapter = new ShopListAdapter(this, R.layout.view_home_item, mShopModels);
//        mShopListAdapter.setUpFetchEnable(true);
        mShopListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

               GoodsCategoryDetailModel goodsCategoryDetailModel =(GoodsCategoryDetailModel)adapter.getItem(position);
                Intent intent = new Intent(ClassifyActivity.this, GoodDetailActivity.class);
                intent.putExtra("goods_id",goodsCategoryDetailModel.getId());
                intent.putExtra("title",goodsCategoryDetailModel.getName());
                startActivity(intent);
            }
        });
        classifyRView.setAdapter(mShopListAdapter);
    }

    private void initClassifyRefresh() {
        classifyRefresh.setRefreshHeader(new ClassicsHeader(this));
        classifyRefresh.setRefreshFooter(new ClassicsFooter(this));
        classifyRefresh.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        classifyRefresh.setEnableFooterFollowWhenLoadFinished(true);
        classifyRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                page++;
                getClassifyData(page,sort_price,sort_sale);

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

//                Log.d("test->>>","刷新完成");
                //请求数据
//                refreshLayout.finishRefresh();  //刷新完成
                page = 1;
                getClassifyData(page,sort_price,sort_sale);

            }
        });
    }


    @Override
    public void initData() {
        super.initData();
        goodCategoryId =  getIntent().getStringExtra("cate_id");
        classifyTitleBar.setTitle(getIntent().getStringExtra("title"));
        getClassifyData(1,0,0);
    }

    private void getClassifyData(final int page1, int sort_price, int sort_sale) {

        HttpParams params = new HttpParams();
        params.put("cate_id",goodCategoryId);
        params.put("page",page1+"");
        if (sort_price > 0){
            params.put("sort_price",sort_price+"");
        }
        if (sort_sale > 0){
            params.put("sort_sale",sort_sale+"");
        }


        Observable<List<GoodsCategoryDetailModel>> observable =EasyHttp.get(Constants.GoodCategoryDetail)
                .params(params)
                .execute(new CallClazzProxy<CustomApiResult<List<GoodsCategoryDetailModel>>, List<GoodsCategoryDetailModel>>(new TypeToken<List<GoodsCategoryDetailModel>>() {}.getType()) {
        });

        observable.subscribe(new BaseSubscriber<List<GoodsCategoryDetailModel>>() {
            @Override
            public void onError(ApiException e) {

                if (page > 1){
                    page--;
                }else {
                    page = 1;
                }

                ToastUtils.show("数据请求失败");

            }

            @Override
            public void onNext(List<GoodsCategoryDetailModel> goodsCategoryDetailModels) {
                super.onNext(goodsCategoryDetailModels);
                if (page1 == 1){
                    mShopModels = goodsCategoryDetailModels;
                    mShopListAdapter.setNewData(mShopModels);
                    classifyRefresh.finishRefresh();
//                    mShopListAdapter.notifyDataSetChanged();
                }else {
                    mShopListAdapter.addData(goodsCategoryDetailModels);
                    if (goodsCategoryDetailModels.size() < 16) {
                        classifyRefresh.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
                    }else {
                        classifyRefresh.finishLoadMore();      //加载完成
                    }

//
                }

            }
        });
    }
}
